﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

// 技能操作界面
public class SkillAtkDlg
{
    public Action<int> OnSkillCallback;

    // <技能索引号，剩余CD时间>
    public Func<int, float> GetLeftCD;
    // <技能索引号，最大CD时间>
    public Func<int, float> GetMaxCD;


    List<SkillPanel> _allSkillPanel = new List<SkillPanel>();

    TimerMgr.Timer _cdTimer;

    public void Init()
    {
        _cdTimer = TimerMgr.Instance.CreateTimer(0.02f, -1, updateAllCD);
        _cdTimer.Start();


        var uiRoot = UIManager.Instance.AddUI("Prefabs/UI/FightUI/SkillAtkDlg", UILayer.FightUI);

        for (int i = 0; i < 5; ++i)
        {
            var btn = uiRoot.FindComponent<Button>("SkillPanel" + (i + 1));
            int index = i;
            btn.onClick.AddListener(
                ()=>
                OnSkillBtnClick(index));

            var panel = new SkillPanel();
            panel.Btn = btn;
            panel.CDImamge = btn.gameObject.FindComponent<Image>("CountDownImage");
            panel.CDText = btn.gameObject.FindComponent<Text>("CountDownLabel");

            _allSkillPanel.Add(panel);
        }
    }

    private void OnSkillBtnClick(int index)
    {
        if (OnSkillCallback != null)
        {
            OnSkillCallback(index);
        }
    }

    // 更新所有技能CD
    private void updateAllCD()
    {
        if (GetLeftCD == null || GetMaxCD == null)
        {
            return;
        }

        // 获取每一个技能的CD
        for (int i = 0; i < 5; ++i)
        {
            updateCD(i, GetLeftCD(i), GetMaxCD(i));
        }
    }

    // 展示CD
    private void updateCD(int index, float leftCD, float maxCD)
    {
        var skillPanel = _allSkillPanel[index];
        if (skillPanel == null)
        {
            return;
        }

        skillPanel.CDImamge.fillAmount = leftCD / maxCD;

        skillPanel.CDText.enabled = leftCD > 0;
        skillPanel.CDText.text = leftCD.ToString("F2");
    }

    private class SkillPanel
    {
        public Button Btn;
        public Image CDImamge;
        public Text CDText;
    }
}
